package com.jackykeke.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;


import com.jackykeke.HBuilder.integrate.SDK_WebApp;
import com.jackykeke.utils.FileSaveUtil;
import com.jackykeke.utils.HttpClientUtil;
import com.jackykeke.utils.ZipUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

import static com.jackykeke.app.AppContants.SYS_DIR_CONF.OnlineWeb_save_dirPath;


/**
 * Created by Jacky F1233804 on 2018/7/13
 * desc：
 */

public class WebAppService extends IntentService {

    public static final String WEBAPPSERVICE_CLASSNAME = "com.jackykeke.service.WebAppService";

    public static final String UNZIP_WEBAPP_OK = "UNZIP_WEBAPP_OK";


    public WebAppService() {
        super(WebAppService.class.getSimpleName());
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public WebAppService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        String url = null;
        if (intent != null) {
            url = intent.getStringExtra("web");
        }
        try {


            checkWebApp(url);

        } catch (IOException e) {
            e.printStackTrace();
//            L.d(WEBAPPSERVICE_CLASSNAME, "报错了------" + e + "");
        }
    }

    public static boolean isSdPresent() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }


//    public static final String OnlineWeb_save_dirPath = getLocalHost_dirPath() + LocalHost_dirpath + "/OnlineWeb/";

    private void checkWebApp(String url) throws IOException {
        int OK = -1;
//        String url = "http://api.idpbg.foxconn.com/download/fanshu.zip";
        String webappName = url.substring(url.lastIndexOf(File.separator) + 1, url.lastIndexOf('.'));

        File file = new File(OnlineWeb_save_dirPath);

        if (!file.exists()) {
            file.mkdir();
        }
        List<String> dirInFiles = FileSaveUtil.getDirectoryName(
                OnlineWeb_save_dirPath.substring(0,
                        OnlineWeb_save_dirPath.lastIndexOf(File.separator)));
        if (dirInFiles != null) {
            for (String s : dirInFiles) {
                if (s.equals(webappName))
                    OK = 0;
                handleUploadImg(OK);
                return;
            }
        }

        boolean success = new HttpClientUtil().downloadFile(url,
                OnlineWeb_save_dirPath, "web" + ".zip");

//        L.d(WEBAPPSERVICE_CLASSNAME, "下载到了没downloadFile？？" + success + "");
        if (success) {
            if (ZipUtils.upZipFile2(OnlineWeb_save_dirPath + "web" + ".zip",
                    OnlineWeb_save_dirPath)) {
                OK = 1;
                renameAndDeletFile(new File(OnlineWeb_save_dirPath
                        + "web" + ".zip"));
            }

        }
        handleUploadImg(OK);

    }

    /**
     * 将文件重命名后删除
     *
     * @param file
     */
    public static void renameAndDeletFile(File file) {
        File reName = new File(file.getAbsolutePath() + System.currentTimeMillis());
        file.renameTo(reName);
        deleteFile(reName);
    }

    /**
     * <li>描述：删除文件夹下的文件 or 单个文件
     * <li>时间：2016年7月11日
     * <li>author： H2601977
     */
    public static void deleteFile(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                file.delete();
                return;
            }
            for (File f : childFile) {
                deleteFile(f);
            }
            file.delete();
        }
    }


    private void handleUploadImg(int ok) {

        Intent intent = new Intent(SDK_WebApp.UNZIP_WEBAPP);
        intent.putExtra(UNZIP_WEBAPP_OK, ok);
        sendBroadcast(intent);

    }

    public static void runWebAppService(Context context, Intent intent, String className) {

        intent.setClassName(context, className);
        context.startService(intent);
    }
}
